package org.changs.nav.ui.nav;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.navi.model.AMapNaviPath;

import org.changs.aplug.plug.InjectEventBusOnResume;
import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.nav.R;
import org.changs.nav.databinding.RoutePlanItemBinding;
import org.changs.nav.databinding.RoutePlanLayoutBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.AmapRouteHelper;
import org.changs.nav.event.RouteItemClickEvent;
import org.changs.nav.event.RouteRefreshEvent;
import org.changs.nav.mvp.RouteListContract;
import org.changs.nav.mvp.RouteListPresenter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import javax.inject.Inject;

/**
 * Created by yincs on 2017/10/14.
 */

public class RouteListFragment extends BaseMapFragment implements RouteListContract.V, InjectEventBusOnResume {

    private static final String TAG_ROUTES = "TAG_ROUTES";
    private static final String TAG_SELECT = "TAG_SELECT";

    public static RouteListFragment newInstance(int[] ints) {
        Bundle args = new Bundle();
        args.putIntArray(TAG_ROUTES, ints);
        RouteListFragment fragment = new RouteListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private RoutePlanLayoutBinding mBinding;
    private int[] mInts;
    private boolean isNaviPathsError = false;
    private RouteAdapter mRouteAdapter = new RouteAdapter();
    @Inject RouteListPresenter mRouteListPresenter;
    @Inject MapSwitchDelegate mMapSwitchDelegate;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.route_plan_layout, container, false);
        mRouteListPresenter.attachView(this);
        mBinding.btnStartNav.setOnClickListener(v -> mRouteListPresenter.clickStartNav(mInts[mRouteAdapter.getSelectPosition()]));
        mBinding.rccRoute.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.rccRoute.setIAdapter(mRouteAdapter);
        mBinding.rccRoute.addFooterView(getContext().getLayoutInflater().inflate(R.layout.route_plan_foot, null));
        mBinding.btnRoutePlanSetting.setOnClickListener(v ->
                getFragmentManager().beginTransaction()
                        .add(R.id.rl_container, new RoutePreferFragment())
                        .addToBackStack(null)
                        .commitAllowingStateLoss());

        int[] ints;
        int select = 0;
        if (savedInstanceState == null) {
            ints = getArguments().getIntArray(TAG_ROUTES);
        } else {
            ints = savedInstanceState.getIntArray(TAG_ROUTES);
            select = savedInstanceState.getInt(TAG_SELECT);
        }
        showRouteList(ints, select);
        return mBinding.getRoot();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mRouteListPresenter.detachView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putIntArray(TAG_ROUTES, mInts);
        outState.putInt(TAG_SELECT, mRouteAdapter.getSelectPosition());
    }

    @Override
    public void showRouteList(int[] ints, int select) {
        mInts = ints;
        ArrayList<AMapNaviPath> aMapNaviPaths = AmapRouteHelper.getAMapNaviPaths(getContext(), ints);
        if (isNaviPathsError) {
            if (aMapNaviPaths != null) {
                mMapSwitchDelegate.switch2RouteList(ints);
                isNaviPathsError = false;
            } else {
                onError("线程计算失败");
                return;
            }
        }
        if (aMapNaviPaths == null) {
            isNaviPathsError = true;
            mRouteListPresenter.calculate();
            return;
        }
        mRouteAdapter.getData().clear();
        mRouteAdapter.getData().addAll(aMapNaviPaths);
        mRouteAdapter.setSelectIndex(select);
        mRouteAdapter.notifyDataSetChanged();
        mBinding.rccRoute.getLayoutManager().scrollToPosition(0);
    }

    @Override
    public void startNavView() {
//        getFragmentManager().popBackStack(MainActivity.TAG_BACK_STACK_DEFAULT, FragmentManager.POP_BACK_STACK_INCLUSIVE);
//        mMapSwitchDelegate.switch2Basics();

        MapNavActivity.start(getContext());
    }

    private class RouteAdapter extends SimpleAdapter<AMapNaviPath, RoutePlanItemBinding> {
        public RouteAdapter() {
            super(R.layout.route_plan_item);
        }

        @Override
        public void onBindViewHolder(RoutePlanItemBinding binding, int position) {
            final AMapNaviPath path = getData().get(position);
            binding.tvType.setText(path.getLabels());
            binding.tvTime.setText(AmapRouteHelper.getCostTime(path.getAllTime()));
            binding.tvDistance.setText(AmapRouteHelper.getCostDistance(path.getAllLength()));
            final boolean select = isSelect(position);
            binding.btnMore.setVisibility(select ? View.VISIBLE : View.GONE);
            binding.getRoot().setOnClickListener(v -> {
                setSelectIndex(position);
                notifyDataSetChanged();
                EventBus.getDefault().post(new RouteItemClickEvent(position));
            });
        }
    }

    @Subscribe
    public void onEvent(RouteRefreshEvent event) {
        mRouteListPresenter.calculate();
    }


    @Override
    protected boolean getOutsideTouchable() {
        return false;
    }
}
